<route lang="json">
{
  "name": "auth",
  "meta": {
    "title": "登录/注册",
    "requiresAuth": false,
    "guestOnly": true
  }
}
</route>

<script setup lang="ts">
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '~/stores/user'

const router = useRouter()
const userStore = useUserStore()

// 当前模式：login 或 register
const mode = ref<'login' | 'register'>('login')

// 表单数据
const formData = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  email: '',
})

// 表单引用
const formRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)

// 记住密码
const rememberMe = ref(false)

// 表单校验规则
const rules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在3到20个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== formData.password) {
          callback(new Error('两次输入的密码不一致'))
        }
        else {
          callback()
        }
      },
      trigger: 'blur',
    },
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: ['blur', 'change'] },
  ],
})

// 切换登录/注册模式
function toggleMode() {
  mode.value = mode.value === 'login' ? 'register' : 'login'
  formRef.value?.resetFields()
}

// 验证表单
async function validateForm() {
  try {
    await formRef.value?.validate()
    return true
  }
  catch (err) {
    const message = mode.value === 'login'
      ? '请填写完整的登录信息'
      : '请填写完整的注册信息'
    ElMessage.warning(message)
    console.warn('表单验证失败', err)
    return false
  }
}

// 处理登录
async function handleLogin() {
  if (!(await validateForm()))
    return

  try {
    loading.value = true
    await userStore.login({
      username: formData.username,
      password: formData.password,
    })

    ElMessage.success('登录成功')
    router.push('/')
  }
  catch (error) {
    const errMsg = (error as Error).message || '登录失败，请稍后重试'
    ElMessage.error(errMsg)
  }
  finally {
    loading.value = false
  }
}

// 处理注册
async function handleRegister() {
  if (!(await validateForm()))
    return

  if (formData.password !== formData.confirmPassword) {
    ElMessage.warning('两次输入的密码不一致')
    return
  }

  try {
    loading.value = true
    await userStore.register({
      username: formData.username,
      password: formData.password,
      email: formData.email,
      name: formData.username,
      role: 'student',
      classId: 0,
    })

    ElMessage.success('注册成功，已自动登录')
    router.push('/')
  }
  catch (error) {
    const errMsg = (error as Error).message || '注册失败，请稍后重试'
    ElMessage.error(errMsg)
  }
  finally {
    loading.value = false
  }
}

// 提交表单
function handleSubmit() {
  if (mode.value === 'login') {
    handleLogin()
  }
  else {
    handleRegister()
  }
}

// 初始化记住的用户名
if (typeof window !== 'undefined') {
  const rememberedUsername = localStorage.getItem('rememberedUsername')
  if (rememberedUsername) {
    formData.username = rememberedUsername
    rememberMe.value = true
  }
}
</script>

<template>
  <div class="auth-container">
    <div class="auth-background">
      <div class="shape shape-1" />
      <div class="shape shape-2" />
      <div class="shape shape-3" />
    </div>

    <div class="auth-box">
      <div class="auth-title">
        <h2>{{ mode === 'login' ? '欢迎回来' : '创建新账户' }}</h2>
        <p class="subtitle">
          {{ mode === 'login' ? '请登录您的账号' : '注册成为用户' }}
        </p>
      </div>

      <el-form ref="formRef" :model="formData" :rules="rules" label-width="0" class="auth-form">
        <el-form-item prop="username">
          <el-input
            v-model="formData.username" :placeholder="mode === 'login' ? '请输入用户名' : '设置用户名'" prefix-icon="User"
            clearable @keyup.enter="handleSubmit"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="formData.password" type="password" :placeholder="mode === 'login' ? '请输入密码' : '设置密码'"
            prefix-icon="Lock" show-password clearable @keyup.enter="handleSubmit"
          />
        </el-form-item>

        <el-form-item v-if="mode === 'register'" prop="confirmPassword">
          <el-input
            v-model="formData.confirmPassword" type="password" placeholder="确认密码" prefix-icon="Lock"
            show-password clearable @keyup.enter="handleSubmit"
          />
        </el-form-item>

        <el-form-item v-if="mode === 'register'" prop="email">
          <el-input
            v-model="formData.email" type="email" placeholder="请输入邮箱" prefix-icon="Message" clearable
            @keyup.enter="handleSubmit"
          />
        </el-form-item>

        <div v-if="mode === 'login'" class="form-options">
          <el-checkbox v-model="rememberMe" class="remember-checkbox">
            记住账号
          </el-checkbox>
          <el-link type="primary" href="#/forgot-password" class="forgot-link">
            忘记密码?
          </el-link>
        </div>

        <el-form-item>
          <el-button type="primary" :loading="loading" class="submit-button" @click="handleSubmit">
            {{ mode === 'login' ? '登录' : '注册' }}
          </el-button>
        </el-form-item>

        <div class="auth-footer">
          <span>
            {{ mode === 'login' ? '没有账号?' : '已有账号?' }}
          </span>
          <el-link type="primary" @click="toggleMode">
            {{ mode === 'login' ? '立即注册' : '立即登录' }}
          </el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<style scoped lang="scss">
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  background: linear-gradient(135deg, var(--ep-color-bg-light) 0%, var(--ep-color-background) 100%);
  position: relative;
  overflow: hidden;

  .auth-background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 0;

    .shape {
      position: absolute;
      border-radius: 50%;
      opacity: 0.8;
      filter: blur(20px);

      &.shape-1 {
        width: 300px;
        height: 300px;
        background: rgba(var(--ep-color-primary-rgb), 0.2);
        top: -100px;
        right: -100px;
        animation: float 8s infinite ease-in-out;
      }

      &.shape-2 {
        width: 200px;
        height: 200px;
        background: rgba(var(--ep-color-success-rgb), 0.2);
        bottom: -50px;
        left: -50px;
        animation: float 6s infinite ease-in-out reverse;
      }

      &.shape-3 {
        width: 150px;
        height: 150px;
        background: rgba(var(--ep-color-warning-rgb), 0.2);
        top: 50%;
        left: 60%;
        animation: float 10s infinite ease-in-out;
      }
    }
  }

  .auth-box {
    width: 420px;
    padding: 40px;
    background-color: var(--ep-color-background);
    border-radius: var(--ep-border-radius-lg);
    box-shadow: var(--ep-shadow-base);
    position: relative;
    z-index: 1;
    animation: fadeIn 0.8s ease-in-out;

    .auth-title {
      text-align: center;
      margin-bottom: var(--ep-spacing-lg);

      h2 {
        font-size: var(--ep-font-size-xl);
        color: var(--ep-color-primary-text);
        margin: var(--ep-spacing-sm) 0;
        font-weight: var(--ep-font-weight-bold);
      }

      .subtitle {
        color: var(--ep-color-secondary-text);
        font-size: var(--ep-font-size-sm);
        margin-top: var(--ep-spacing-xs);
      }
    }

    .auth-form {
      :deep(.el-input__wrapper) {
        border-radius: var(--ep-border-radius-base);
        padding: 0 var(--ep-spacing-base);
        height: 50px;
        box-shadow: 0 0 0 var(--ep-border-width) var(--ep-color-border);
        transition: all var(--ep-transition-duration);

        &:hover,
        &:focus,
        &.is-focus {
          box-shadow: 0 0 0 var(--ep-border-width) var(--ep-color-primary);
        }
      }

      :deep(.el-input__prefix-inner) {
        color: var(--ep-color-placeholder);
      }

      :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
        background-color: var(--ep-color-primary);
        border-color: var(--ep-color-primary);
      }

      :deep(.el-checkbox__label) {
        color: var(--ep-color-regular);
      }

      .form-options {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: var(--ep-spacing-sm) 0 var(--ep-spacing-base);
        padding: 0 var(--ep-spacing-xs);

        .remember-checkbox {
          margin-right: auto;
        }

        .forgot-link {
          color: var(--ep-color-primary);
          margin-left: var(--ep-spacing-base);
          font-size: var(--ep-font-size-sm);

          &:hover {
            color: var(--ep-color-primary-light);
          }
        }
      }

      .submit-button {
        width: 100%;
        height: 50px;
        border-radius: var(--ep-border-radius-base);
        font-size: var(--ep-font-size-base);
        font-weight: var(--ep-font-weight-medium);
        background-color: var(--ep-color-primary);
        border-color: var(--ep-color-primary);
        transition: all var(--ep-transition-duration);

        &:hover,
        &:focus {
          background-color: var(--ep-color-primary-light);
          border-color: var(--ep-color-primary-light);
          transform: translateY(-2px);
          box-shadow: 0 5px 15px rgba(var(--ep-color-primary-rgb), 0.3);
        }

        &:active {
          transform: translateY(0);
        }
      }

      .auth-footer {
        text-align: center;
        margin-top: var(--ep-spacing-base);
        color: var(--ep-color-regular);
        font-size: var(--ep-font-size-sm);
        display: flex;
        justify-content: center;
        align-items: center;

        .el-link {
          margin-left: var(--ep-spacing-xs);
          color: var(--ep-color-primary);
          font-weight: var(--ep-font-weight-medium);
          font-size: var(--ep-font-size-sm);
          transition: color var(--ep-transition-duration);
          position: relative;
          padding-bottom: 3px;
          min-width: fit-content;
          white-space: nowrap;
          flex-shrink: 0;

          &::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 0;
            width: 100%;
            height: 1px;
            background: currentColor;
            transform: scaleX(0);
            transform-origin: center;
            transition: transform var(--ep-transition-duration);
          }

          &:hover {
            color: var(--ep-color-primary-light);

            &::after {
              transform: scaleX(1);
            }
          }
        }
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes float {
  0% {
    transform: translateY(0) rotate(0deg);
  }

  50% {
    transform: translateY(-20px) rotate(5deg);
  }

  100% {
    transform: translateY(0) rotate(0deg);
  }
}
</style>
